package com.cash.app.ui.auth

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.os.Environment
import android.provider.MediaStore
import android.view.View
import android.widget.Toast
import androidx.activity.result.contract.ActivityResultContracts
import androidx.activity.viewModels
import androidx.core.content.FileProvider
import androidx.core.view.isVisible
import coil3.load
import coil3.request.placeholder
import com.cash.app.R
import com.cash.app.base.BaseActivity
import com.cash.app.constant.AppConstant.AUTH_AADHAAR_BACK
import com.cash.app.constant.AppConstant.AUTH_AADHAAR_FRONT
import com.cash.app.constant.AppConstant.AUTH_PAN_CARD
import com.cash.app.constant.AppConstant.AUTH_SELFIE
import com.cash.app.custom.AppActionBar
import com.cash.app.databinding.AcAuthBasicBinding
import com.cash.app.ui.auth.model.OcrACardBackModel
import com.cash.app.ui.auth.model.OcrACardFrontModel
import com.cash.app.ui.auth.model.OcrPCardFrontModel
import com.cash.app.utils.ImagePickerUtils
import com.cash.app.utils.TLog
import com.cash.app.utils.addHttpPrefix
import com.cash.app.utils.hide
import com.cash.app.utils.visible
import java.io.File
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale

class AuthBasicActivity : BaseActivity() {

    private val TAG = "AuthBasicActivity"

    private var isOnlyShow = false

    companion object {
        private const val EXTRA_ONLY_SHOW = "isOnlyShow"

        fun start(context: Context, isOnlyShow: Boolean = false) {
            val intent = Intent(context, AuthBasicActivity::class.java).apply {
                putExtra(EXTRA_ONLY_SHOW, isOnlyShow)
            }
            context.startActivity(intent)
        }
    }

    private lateinit var binding: AcAuthBasicBinding
    private val viewModel: AuthBasicViewModel by viewModels()
    private var selfieUri: Uri? = null
    private var selfieBase64: String? = null

    private var aadhaarFrontBase64: String? = null
    private var aadhaarFrontOcrStatus = false

    private var aadhaarBackBase64: String? = null
    private var aadhaarBackOcrStatus = false

    private var panCardBase64: String? = null
    private var panCardOcrStatus = false

    private var ocrACardFrontInfo: OcrACardFrontModel? = null
    private var ocrACardBackInfo: OcrACardBackModel? = null
    private var ocrPCardFrontInfo: OcrPCardFrontModel? = null

    private var currentImageType: Int = -1

    override fun setViewBind() {
        binding = AcAuthBasicBinding.inflate(layoutInflater)
    }

    override fun getLayoutView(): View = binding.root

    override fun getAppActionBar(): AppActionBar = binding.actionBar

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        initView()
        isOnlyShow = intent.getBooleanExtra(EXTRA_ONLY_SHOW, false)
        if (isOnlyShow) {
            viewModel.getAuthInfoByBasic()
        }
    }

    private fun initView() {
        initListener()
        initObserver()
    }

    private fun initListener() {
        binding.selfieRl.setOnClickListener {
            if (isOnlyShow) {
                return@setOnClickListener
            }
            currentImageType = AUTH_SELFIE
            takeSelfie()
        }

        binding.ivAadhaarFront.setOnClickListener {
            if (isOnlyShow) {
                return@setOnClickListener
            }
            currentImageType = AUTH_AADHAAR_FRONT
            binding.selectImgCl.visible()
        }

        binding.ivAadhaarBack.setOnClickListener {
            if (isOnlyShow) {
                return@setOnClickListener
            }
            currentImageType = AUTH_AADHAAR_BACK
            binding.selectImgCl.visible()
        }

        binding.ivPanCard.setOnClickListener {
            if (isOnlyShow) {
                return@setOnClickListener
            }
            currentImageType = AUTH_PAN_CARD
            binding.selectImgCl.visible()
        }

        binding.btnSubmit.setOnClickListener {
            if (isOnlyShow) {
                return@setOnClickListener
            }
            submitStepOne()
        }
        binding.selectImgCl.setOnClickListener {
            binding.selectImgCl.hide()
        }
        binding.takePhotoLl.setOnClickListener {
            takeSelfie(false)
            binding.selectImgCl.hide()
        }
        binding.selectPhotoLl.setOnClickListener {
            pickImage()
            binding.selectImgCl.hide()
        }
    }


    override fun onBackPressed() {
        if (binding.selectImgCl.isVisible) {
            binding.selectImgCl.hide()
        } else {
            super.onBackPressed()
        }
    }

    private fun initObserver() {
//        viewModel.isLoading.observe(this) { isLoading ->
//            binding.loadingLayout.visibility = if (isLoading) View.VISIBLE else View.GONE
//        }
        viewModel.aFrontOcrStatus.observe(this) { isSuccess ->
            if (isSuccess) {
                binding.aadhaarFrontStatus.setImageResource(R.mipmap.right)
            } else {
                binding.aadhaarFrontStatus.setImageResource(R.mipmap.error)
            }
        }
        viewModel.aBackOcrStatus.observe(this) { isSuccess ->
            if (isSuccess) {
                binding.aadhaarBackStatus.setImageResource(R.mipmap.right)
            } else {
                binding.aadhaarBackStatus.setImageResource(R.mipmap.error)
            }
        }
        viewModel.pFontOcrStatus.observe(this) { isSuccess ->
            if (isSuccess) {
                binding.panCardStatus.setImageResource(R.mipmap.right)
            } else {
                binding.panCardStatus.setImageResource(R.mipmap.error)
            }
        }

        viewModel.imageBase64.observe(this) { pair ->
            pair?.let { (type, base64) ->
                TLog.d("Image type: $type, base64 success", TAG)
                when (type) {
                    AUTH_SELFIE -> {
                        selfieBase64 = base64[0]
                        binding.loadingLayout.hide()
                    }

                    AUTH_AADHAAR_FRONT -> {
                        aadhaarFrontBase64 = base64[0]
                        viewModel.getOcrByACardFront(aadhaarFrontBase64!!, AUTH_AADHAAR_FRONT)
                    }

                    AUTH_AADHAAR_BACK -> {
                        aadhaarBackBase64 = base64[0]
                        viewModel.getOcrByACardBack(aadhaarBackBase64!!, AUTH_AADHAAR_BACK)
                    }

                    AUTH_PAN_CARD -> {
                        panCardBase64 = base64[0]
                        viewModel.getOcrByPCardFront(panCardBase64!!, AUTH_PAN_CARD)
                    }
                }
            }
        }

        viewModel.ocrACardFrontInfo.observe(this) { aCardFrontOcr ->
            TLog.d("ACardFront orc success,info=${aCardFrontOcr}", TAG)
            aadhaarFrontOcrStatus = true
            ocrACardFrontInfo = aCardFrontOcr.cardInfo
        }
        viewModel.ocrACardBackInfo.observe(this) { aCardBackOcr ->
            TLog.d("ACardBack orc success,info=${aCardBackOcr}", TAG)
            aadhaarBackOcrStatus = true
            ocrACardBackInfo = aCardBackOcr.cardInfo
        }
        viewModel.ocrPCardFrontInfo.observe(this) { pCardFrontOcr ->
            TLog.d("PCardFront orc success,info=${pCardFrontOcr}", TAG)
            panCardOcrStatus = true
            ocrPCardFrontInfo = pCardFrontOcr.cardInfo
        }
        viewModel.submitSuccess.observe(this) { isSuccess ->
            if (isSuccess) {
                val intent = Intent(this, AuthPersonalActivity::class.java)
                startActivity(intent)

                setResult(RESULT_OK)
                finish()
            }
        }
        viewModel.authBaseInfo.observe(this) { basicInfo ->
            binding.apply {
                btnSubmit.hide()
                selfieStatus.hide()
                selfie.load(basicInfo.baseHeaderImg.addHttpPrefix()) {
                    placeholder(R.mipmap.auth_img_bg)
                }
                aadhaarFrontStatus.hide()
                ivAadhaarFront.load(basicInfo.baseAdFrontImg.addHttpPrefix()) {
                    placeholder(R.mipmap.auth_img_bg)
                }
                aadhaarBackStatus.hide()
                ivAadhaarBack.load(basicInfo.baseAdBackImg.addHttpPrefix()) {
                    placeholder(R.mipmap.auth_img_bg)
                }
                panCardStatus.hide()
                ivPanCard.load(basicInfo.basePanFrontImg.addHttpPrefix()) {
                    placeholder(R.mipmap.auth_img_bg)
                }
            }
        }
    }

    private fun pickImage() {
        val intent = ImagePickerUtils.getImagePickerIntent(false, 1)
        imagePickerLauncher.launch(intent)
    }

    private fun takeSelfie(isFront: Boolean = true) {
        val photoFile = createImageFile()
        photoFile.also { file ->
            selfieUri = FileProvider.getUriForFile(
                this, "${packageName}.provider", file
            )
            val intent = Intent(MediaStore.ACTION_IMAGE_CAPTURE).apply {
                putExtra(MediaStore.EXTRA_OUTPUT, selfieUri)
                if (isFront) {
                    putExtra("android.intent.extras.CAMERA_FACING", 1)
                    putExtra("android.intent.extras.LENS_FACING_FRONT", 1)
                    putExtra("android.intent.extra.USE_FRONT_CAMERA", true)
                }
            }
            takeSelfieLauncher.launch(intent)
        }
    }

    private val takeSelfieLauncher = registerForActivityResult(
        ActivityResultContracts.StartActivityForResult()
    ) { result ->
        if (result.resultCode == Activity.RESULT_OK) {
            selfieUri?.let { uri ->
                when (currentImageType) {
                    AUTH_SELFIE -> {
                        binding.selfie.setImageURI(uri)
                        binding.selfieStatus.setImageResource(R.mipmap.right)
                        viewModel.processImageBase64(this, uri, AUTH_SELFIE)
                    }

                    AUTH_AADHAAR_FRONT -> {
                        binding.ivAadhaarFront.setImageURI(uri)
                        viewModel.processImageBase64(this, uri, AUTH_AADHAAR_FRONT)
                    }

                    AUTH_AADHAAR_BACK -> {
                        binding.ivAadhaarBack.setImageURI(uri)
                        viewModel.processImageBase64(this, uri, AUTH_AADHAAR_BACK)
                    }

                    AUTH_PAN_CARD -> {
                        binding.ivPanCard.setImageURI(uri)
                        viewModel.processImageBase64(this, uri, AUTH_PAN_CARD)
                    }
                }
            }
        }
    }

    private val imagePickerLauncher = registerForActivityResult(
        ActivityResultContracts.StartActivityForResult()
    ) { result ->
        if (result.resultCode == Activity.RESULT_OK) {
            result.data?.let { data ->
                val images = ImagePickerUtils.handleImagePickerResult(data, 1)
                if (images.isNotEmpty()) {
                    val uri = images[0]
                    when (currentImageType) {
                        AUTH_AADHAAR_FRONT -> {
                            binding.ivAadhaarFront.setImageURI(uri)
                            viewModel.processImageBase64(this, uri, AUTH_AADHAAR_FRONT)
                        }

                        AUTH_AADHAAR_BACK -> {
                            binding.ivAadhaarBack.setImageURI(uri)
                            viewModel.processImageBase64(this, uri, AUTH_AADHAAR_BACK)
                        }

                        AUTH_PAN_CARD -> {
                            binding.ivPanCard.setImageURI(uri)
                            viewModel.processImageBase64(this, uri, AUTH_PAN_CARD)
                        }
                    }
                }
            }
        }
    }

    private fun createImageFile(): File {
        val timeStamp = SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(Date())
        val storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES)
        return File.createTempFile(
            "SELFIE_${timeStamp}_", ".jpg", storageDir
        )
    }

    private fun submitStepOne() {
        var toastMsg = ""
        if (selfieBase64.isNullOrEmpty()) {
            toastMsg = getString(R.string.auth_selfie_required)
        } else if (aadhaarFrontBase64.isNullOrEmpty() || !aadhaarFrontOcrStatus) {
            toastMsg = getString(R.string.auth_aadhaar_front_required)
        } else if (aadhaarBackBase64.isNullOrEmpty() || !aadhaarBackOcrStatus) {
            toastMsg = getString(R.string.auth_aadhaar_back_required)
        } else if (panCardBase64.isNullOrEmpty() || !panCardOcrStatus) {
            toastMsg = getString(R.string.auth_pan_required)
        }
        if (toastMsg.isNotEmpty()) {
            Toast.makeText(this, toastMsg, Toast.LENGTH_SHORT).show()
            return
        }
        viewModel.submitStepOne(
            selfieBase64 = selfieBase64!!
        )
    }

    override fun onDestroy() {
        super.onDestroy()
    }
} 